package com.rayboo.xhs_share

import androidx.annotation.NonNull
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.xingin.xhssharesdk.XhsShareSdkTools
import com.xingin.xhssharesdk.callback.XhsShareCallback
import com.xingin.xhssharesdk.callback.XhsShareRegisterCallback
import com.xingin.xhssharesdk.core.XhsShareSdk
import com.xingin.xhssharesdk.model.config.XhsShareGlobalConfig
import com.xingin.xhssharesdk.model.sharedata.*
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** XhsSharePlugin */
class XhsSharePlugin: FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private lateinit var channel : MethodChannel

  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "xhs_share")
    channel.setMethodCallHandler(this)
  }

  override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
    if (call.method == "getPlatformVersion") {
      result.success("Android ${android.os.Build.VERSION.RELEASE}")
    } else if (call.method == "sendData") {
        var articleTitle = call.argument("title") as String?
        var articleContent = call.argument("articleContent") as String?
        val articlePicJsonArray = call.argument("articlePic") as String?
        val articleType = call.argument("articleType") as Int?

        Log.i("onMethodCall","title= $articleTitle  ")
        Log.i("onMethodCall","articleContent= $articleContent  ")
        Log.i("onMethodCall","articleType= $articleType  ")
        Log.i("onMethodCall","articlePic= $articlePicJsonArray  ")

        val gson = Gson()

        val listType: Type = object : TypeToken<List<String>>() {}.type
        val articlePicList : List<String?> = gson.fromJson(articlePicJsonArray, listType)
        Log.i("onMethodCall","articlePicList = ${articlePicList.size}  ")
        var map = mapOf("title" to "$articleTitle", "articleContent" to "$articleContent", "articlePic" to "$articlePicList")

        initXhsSDK(articleTitle, articleContent, articlePicList, articleType)
        result.success(map)
      } else if (call.method == "isInstalled") {
        isInstalled(result);

    } else {
      result.notImplemented()
    }
  }

  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }

  // 是否安装小红书
  private fun isInstalled (result: MethodChannel.Result) {
    var isInstalled = XhsShareSdkTools.isXhsInstalled(activity.applicationContext)
    result.success(isInstalled)
  }

  // 小红书分享sdk
  private fun initXhsSDK(articleTitle : String?, articleContent: String?, articlePicList : List<String?>, articleType : Int?){
    Log.i("init","sendData init xhs")
    XhsShareSdk.registerApp(activity.applicationContext, "4009cdc26af8992854022e30c047ad03",
      XhsShareGlobalConfig().setEnableLog(true).setClearCacheWhenShareComplete(true),
      object : XhsShareRegisterCallback {
        override fun onSuccess() {
          Log.i("xhs","注册成功")
        }

        override fun onError(
          errorCode: Int,
          errorMessage: String,
          @Nullable exception: Exception?
        ) {
          Log.i("xhs","注册失败！errorCode: $errorCode errorMessage: $errorMessage exception: $exception")
        }
      })
    var imageUrlList : MutableList<XhsImageResourceBean?> = ArrayList()

    if(articleType == 1){
      articlePicList.forEach{ element ->
        imageUrlList.add(XhsImageResourceBean.fromUrl(element))
      }
    }

    var isInstalled = XhsShareSdkTools.isXhsInstalled(activity.applicationContext)
    if(isInstalled){
      var note : XhsNote? = XhsNote()
      activity.runOnUiThread {
        if (articleType == 1) {
          note = XhsNote().apply {
            title = "$articleTitle"
            content = "$articleContent"
            imageInfo = XhsImageInfo(imageUrlList)
          }
        } else if (articleType == 2) {
          note = XhsNote().apply {
            title = "$articleTitle"
            content = "$articleContent"
            videoInfo = XhsVideoInfo(
              XhsVideoResourceBean.fromUrl(articlePicList[0]),     // 视频
              XhsImageResourceBean.fromUrl(articlePicList[1])      // 封面
            )
          }
        } else {
          note = XhsNote().apply {
            title = "$articleTitle"
            content = "$articleContent"
          }
        }

        val sessionId = XhsShareSdk.shareNote(activity.applicationContext, note)

        XhsShareSdk.setShareCallback(object : XhsShareCallback {
          override fun onSuccess(p0: String?) {
            Log.i("xhs", "onSuccess: 分享成功！！！ $p0")

            var map = mapOf("shareCallback" to true)
            channel.invokeMethod("xhsShareCallback", map)
            XhsShareSdk.setShareCallback(null)
          }

          override fun onError(p0: String, p1: Int, p2: String, p3: Throwable?) {
            Log.i("xhs", "onError: 分享失败！！！$p0")
            Log.i("xhs", "onError: 分享失败！！！$p1")
            Log.i("xhs", "onError: 分享失败！！！$p2")
            Log.i("xhs", "onError: 分享失败！！！$p3")

            var map = mapOf("shareCallback" to false)
            channel.invokeMethod("xhsShareCallback", map)
            XhsShareSdk.setShareCallback(null)
          }
        })
      }

    }
  }

}
